#/bin/bash
## prepare , need install before

VERSION_STR="1.0.0"
VERSION_NEW=""
RELATIVE_DIR=""
function now_dir() {
    DIRS=("" "../")
    for D in ${DIRS[*]}; do
        if [ -f "${D}version" ]; then
            RELATIVE_DIR=${D}
            break
        fi
    done
}

## load version
function read_version() {
    VERSION_STR=$(cat ${RELATIVE_DIR}version)
    echo "release version: ${VERSION_STR}"

    version_str=${VERSION_STR#*v}
    MAJOR=$(echo $version_str | cut -d '.' -f 1)
    MINOR=$(echo $version_str | cut -d '.' -f 2)
    PATCH=$(echo $version_str | cut -d '.' -f 3)
    PATCH=$(expr ${PATCH} + 1)
    VERSION_NEW="${MAJOR}.${MINOR}.${PATCH}"
}

## npm build
function npm_build() {
    export VERSION=${VERSION_STR}
    npm run build
}

## sign
function sign() {
    source ${RELATIVE_DIR}.env
    npm run sign
}

function tag() {
    git tag ${VERSION_STR}
}

## update version
function update() {
    ## update version file
    cat /dev/null >${RELATIVE_DIR}version && echo ${VERSION_NEW} >${RELATIVE_DIR}version
    ## update package.json 'version'
    sed -i "" "s/\"version\": \"${VERSION_STR}\"/\"version\": \"${VERSION_NEW}\"/g" ${RELATIVE_DIR}package.json
    ## update package-lock.json 'version'
    sed -i "" "s/\"version\": \"${VERSION_STR}\"/\"version\": \"${VERSION_NEW}\"/g" ${RELATIVE_DIR}package-lock.json
}

function bump_ver() {
    git commit -m 'bump version'
}

function package() {
    cd ${RELATIVE_DIR}dist && zip mogdb-${VERSION_STR}-datasource.zip * -r
}

now_dir
read_version
npm_build
/bin/bash ${RELATIVE_DIR}scripts/compile-backend.sh
tag
update
package
# sign
# bump_ver
